package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.common.BeanCopier;
import com.mk.common.Config;
import com.mk.log.annotation.Log;
import com.mk.mapper.DirMapper;
import com.mk.model.entity.*;
import com.mk.model.request.DirRequest;
import com.mk.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 10:06 AM 3/15/18
 */
@Service
public class DirService extends BaseService<DirMapper,Dir> implements IDirService {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoleDirService roleDirService;
    @Autowired
    private IPacService pacService;
    @Autowired
    private IFileInfoService fileInfoService;
    @Autowired
    private IRoleDirDService roleDirDService;
    @Autowired
    private IRoleDirWService roleDirWService;

    @Override
    @Transactional
    @Log(module = "文件夹管理",description = "添加文件夹信息")
    public Dir saveDir(DirRequest request) {
        if(request == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入添加的文件夹信息");
        if(StringUtils.isEmpty(request.getTitle()))
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"添加文件夹信息时名称不可为空");
        List<Role> roles = roleService.findByUserId(request.getUserId());
        List<Dir> exists = findDirsByParentAndTitle(request.getParent(),request.getTitle());
        if(!CollectionUtils.isEmpty(exists))
            throw new ApplicationException(StatusCode.UNIQUE_KE.getCode(),"该目录下已存在同名文件夹(如果该同名文件夹不可见，可能您对该同名文件没有查看权限)");
        Dir dir = BeanCopier.copy(request,Dir.class);
        Date nowDate = new Date();
        dir.setCreateTime(nowDate);
        dir.setUpdateTime(nowDate);
        if(super.insert(dir)) {
            if(!CollectionUtils.isEmpty(roles)){
                //自己创建的文件自己有读写删的操作
                for (Role role : roles) {
                    RoleDirR roleDirR = new RoleDirR();
                    roleDirR.setRoleId(role.getId());
                    roleDirR.setrDir(dir.getId());
                    roleDirService.save(roleDirR);
                    roleDirDService.save(role.getId(),dir.getId());
                    roleDirWService.save(role.getId(),dir.getId());
                }
            }
            return dir;
        }else
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"添加文件夹失败");
    }

    @Override
    @Transactional
    @Log(module = "文件夹管理",description = "编辑文件夹信息")
    public Boolean updateDir(DirRequest request) {
        if(ObjectUtils.isEmpty(request) || request.getId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入需要修改的文件夹信息");
        Dir existById = get(request.getId(),null);
        if(existById == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"编辑的文件夹信息不存在");
        List<Dir> dirs = findDirsByParentAndTitle(request.getParent(),request.getTitle());
        if(!CollectionUtils.isEmpty(dirs)){
            for (Dir dir : dirs) {
                if(!dir.getId().equals(request.getId())){
                    throw new ApplicationException(StatusCode.CONFLICT.getCode(),"该目录下已存在同名文件夹(如果同名文件夹不可见，可能您对该同名文件夹没有查看权限)");
                }
            }
        }
        Dir dir = BeanCopier.copy(request,Dir.class);
        dir.setUpdateTime(new Date());
        return super.updateById(dir);
    }

    @Override
    @Transactional
    @Log(module = "文件夹管理",description = "删除文件夹信息")
    public Boolean deleteDir(Long id) {
        if(id == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择需要删除的文件夹");
        Dir existById = get(id,null);
        if(existById == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"删除的文件件信息不存在");
        List<Pac> pacs = pacService.getByDirId(id);
        if(!CollectionUtils.isEmpty(pacs))
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"文件夹下有资料包，无法删除");
        existById.setUpdateTime(new Date());
        existById.setIsDeleted(Config.ABLE_CONFIG.UNABLE);
        return super.updateById(existById);
    }

    @Override
    public Dir get(Long id,Long userId) {
        Dir dir = super.selectById(id);
        if(userId != null) {
            if (dir != null) {
                List<Role> roles = roleService.findByUserId(userId);
                Role role = null;
                if(!CollectionUtils.isEmpty(roles))
                    role = roles.get(0);
                dir.setrGrant(roleDirService.findByDir(role.getId(), id) != null ? 1 : 0);
                dir.setwGrant(roleDirWService.findByDir(role.getId(), id) != null ? 1 : 0);
                dir.setdGrant(roleDirWService.findByDir(role.getId(), id) != null ? 1 : 0);
            }
        }
        return dir;
    }

    @Override
    public List<Dir> findDirsByParentAndTitle(Long parent, String title) {
        return super.selectList(new EntityWrapper<Dir>()
                .eq("parent",parent)
                .eq("title",title)
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE));
    }

    @Override
    public List<Dir> findAll(Long userId) {
        List<Role> roles = roleService.findByUserId(userId);
        Role role = null;
        if(!CollectionUtils.isEmpty(roles))
            role = roles.get(0);
        List<Dir> dirs = super.selectList(new EntityWrapper<Dir>()
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE));
        if(role != null) {
            if (!CollectionUtils.isEmpty(dirs)) {
                for (Dir dir : dirs) {
                    dir.setrGrant(roleDirService.findByDir(role.getId(), dir.getId()) != null ? 1 : 0);
                    dir.setwGrant(roleDirWService.findByDir(role.getId(), dir.getId()) != null ? 1 : 0);
                    dir.setdGrant(roleDirWService.findByDir(role.getId(), dir.getId()) != null ? 1 : 0);
                }
            }
        }
        return dirs;
    }

    @Override
    @Log(module = "文件夹管理",description = "按照关键词搜索相关文件夹及文件")
    public List<Search> keySearch(String key,Long userId) {
        List<Pac> pacs = pacService.keySearch(key);
        List<FileInfo> fileInfos = fileInfoService.keySearch(key);
        List<Search> searches = new ArrayList<>();
        List<Role> roles = roleService.findByUserId(userId);
        Role role = null;
        if(!CollectionUtils.isEmpty(roles))
            role = roles.get(0);
        if (!CollectionUtils.isEmpty(pacs)) {
            int len = pacs.size();
            for (int i = 0; i < len; i++) {
                Search search = new Search();
                Dir dir = get(pacs.get(i).getDirId(),null);
                if(dir != null){
                    if(roleDirService.findByDir(role.getId(),dir.getId()) != null) {
                        search.setDirId(dir.getId());
                        search.setDirTitle(dir.getTitle());
                        search.setTagId(pacs.get(i).getId());
                        search.setTagTitle(pacs.get(i).getTitle());
                        searches.add(search);
                    }
                }
            }
        }
        if(!CollectionUtils.isEmpty(fileInfos)){
            int len = fileInfos.size();
            for (int i = 0; i < len; i++) {
                FileInfo fileInfo = fileInfos.get(i);
                Search search = new Search();
                Dir dir = get(fileInfo.getDirId(),null);
                Pac pac = pacService.get(fileInfo.getPacId());
                if(dir != null && pac != null){
                    if(roleDirService.findByDir(role.getId(),dir.getId()) != null) {
                        search.setDirId(dir.getId());
                        search.setDirTitle(dir.getTitle());
                        search.setTagId(pac.getId());
                        search.setTagTitle(pac.getTitle());
                        search.setFileId(fileInfo.getId());
                        search.setFileTitle(fileInfo.getName());
                        searches.add(search);
                    }
                }
            }
        }
        return searches;
    }
}
